using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Threading.Tasks;
using WorkFlowCore.BusinessDemo.Web.Data;
using WorkFlowCore.BusinessDemo.Web.Entities;
using WorkFlowCore.BusinessDemo.Web.Models;
using WorkFlowCore.BusinessDemo.Web.Services.Adapters;
using WorkFlowCore.BusinessDemo.Web.Models.AdapterDtos; // For DTOs like CreateWorkTaskWithDefaultVersionInputDto
using System.Collections.Generic;
using WorkTaskStatus = WorkFlowCore.BusinessDemo.Web.Entities.WorkTaskStatus;

namespace WorkFlowCore.BusinessDemo.Web.Controllers
{
    public class OfficialSealApplicationController : BaseController
    {
        private const string OfficialSealApplicationEntityFullName = "OfficialSealApplication";
        private readonly BusinessDemoDbContext _context;
        private readonly IWorkTaskAdapterService _workTaskAdapterService;

        public OfficialSealApplicationController(
            BusinessDemoDbContext context,
            IWorkTaskAdapterService workTaskAdapterService)
        {
            _context = context;
            _workTaskAdapterService = workTaskAdapterService;
        }

        // GET: OfficialSealApplication
        public async Task<IActionResult> Index(string searchTerm, int pageNumber = 1, int pageSize = 10)
        {
            var query = _context.OfficialSealApplications.AsQueryable();

            if (!string.IsNullOrEmpty(searchTerm))
            {
                query = query.Where(s => s.ApplicantName.Contains(searchTerm) || s.Reason.Contains(searchTerm));
            }

            var totalItems = await query.CountAsync();
            var applicationEntities = await query.OrderByDescending(s => s.Id)
                                           .Skip((pageNumber - 1) * pageSize)
                                           .Take(pageSize)
                                           .ToListAsync();

            var applicationViewModels = new List<OfficialSealApplicationViewModel>();
            foreach (var entity in applicationEntities)
            {
                var vm = new OfficialSealApplicationViewModel
                {
                    Id = entity.Id,
                    ApplicantName = entity.ApplicantName,
                    ApplicantDepartment = entity.ApplicantDepartment,
                    ApplicationDate = entity.ApplicationDate,
                    SealType = entity.SealType,
                    Reason = entity.Reason,
                    UsageStartDate = entity.UsageStartDate,
                    UsageEndDate = entity.UsageEndDate,
                    Quantity = entity.Quantity,
                    AttachedFilesInfo = entity.AttachedFilesInfo,
                    WorkTaskId = entity.WorkTaskId,
                    CreatedTime = entity.CreatedTime,
                    UpdatedTime = entity.UpdatedTime,
                    CreatorUserId = entity.CreatorUserId
                };
                await PopulateWorkTaskStatusAsync(vm, entity.Id.ToString(), entity.WorkTaskId);
                applicationViewModels.Add(vm);
            }

            var pagedViewModel = new PagedResult<OfficialSealApplicationViewModel>
            {
                Items = applicationViewModels,
                PageIndex = pageNumber,
                PageSize = pageSize,
                TotalCount = totalItems
            };

            ViewBag.SearchTerm = searchTerm;
            return View(pagedViewModel);
        }

        private async Task PopulateWorkTaskStatusAsync(OfficialSealApplicationViewModel viewModel, string entityId, string? appWorkTaskId)
        {
            //优先通过 EntityFullName 和 EntityKeyValue 查询最新的状态记录
            var workTaskState = await _context.WorkTaskStateInfos
                .Where(wts => wts.EntityFullName == OfficialSealApplicationEntityFullName && wts.EntityKeyValue == entityId)
                .OrderByDescending(wts => wts.CreatedTime)
                .FirstOrDefaultAsync();

            if (workTaskState != null)
            {
                viewModel.CurrentWorkTaskStatus = workTaskState.WorkTaskStatus.ToString(); // Enum to string
                viewModel.CurrentWorkTaskStatusDisplay = GetWorkTaskStatusDisplayName(workTaskState.WorkTaskStatus);
                // viewModel.WorkTaskId is already set from the application entity.
                // If workTaskState had a WorkTaskId field and it was considered more authoritative, we could update viewModel.WorkTaskId here.
            }
            else if (!string.IsNullOrEmpty(appWorkTaskId))
            {
                // Fallback or initial state if WorkTaskStateInfo is not yet populated but WorkTaskId exists on application
                // This case might indicate a very recently created task where the state event hasn't been processed.
                // Or, if the primary way to link is indeed the WorkTaskId stored in OfficialSealApplication.
                // For now, we assume WorkTaskStateInfo is the authority if it exists for the entity.
                // If no WorkTaskStateInfo, but appWorkTaskId exists, it's likely "Pending" or "Processing" but we can't be sure without more context.
                viewModel.CurrentWorkTaskStatusDisplay = "处理中/状态同步中"; // A generic message
            }
            else
            {
                viewModel.CurrentWorkTaskStatusDisplay = "未提交"; // No WorkTaskId and no state record
            }
        }

        private string GetWorkTaskStatusDisplayName(WorkTaskStatus status)
        {
            return status switch
            {
                WorkTaskStatus.Pending => "待处理",
                WorkTaskStatus.Processing => "处理中",
                WorkTaskStatus.Processed => "已完成",
                WorkTaskStatus.Canceled => "已取消",
                WorkTaskStatus.Rejected => "已驳回",
                _ => status.ToString(),
            };
        }

        // GET: OfficialSealApplication/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var officialSealApplication = await _context.OfficialSealApplications
                .FirstOrDefaultAsync(m => m.Id == id);

            if (officialSealApplication == null)
            {
                return NotFound();
            }

            var viewModel = new OfficialSealApplicationViewModel
            {
                Id = officialSealApplication.Id,
                ApplicantName = officialSealApplication.ApplicantName,
                ApplicantDepartment = officialSealApplication.ApplicantDepartment,
                ApplicationDate = officialSealApplication.ApplicationDate,
                SealType = officialSealApplication.SealType,
                Reason = officialSealApplication.Reason,
                UsageStartDate = officialSealApplication.UsageStartDate,
                UsageEndDate = officialSealApplication.UsageEndDate,
                Quantity = officialSealApplication.Quantity,
                AttachedFilesInfo = officialSealApplication.AttachedFilesInfo,
                WorkTaskId = officialSealApplication.WorkTaskId,
                CreatedTime = officialSealApplication.CreatedTime,
                UpdatedTime = officialSealApplication.UpdatedTime,
                CreatorUserId = officialSealApplication.CreatorUserId
            };

            await PopulateWorkTaskStatusAsync(viewModel, officialSealApplication.Id.ToString(), officialSealApplication.WorkTaskId);

            return View(viewModel);
        }

        // GET: OfficialSealApplication/PublicDetails/5
        [AllowAnonymous]
        public async Task<IActionResult> PublicDetails(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var officialSealApplication = await _context.OfficialSealApplications
                .FirstOrDefaultAsync(m => m.Id == id);

            if (officialSealApplication == null)
            {
                return NotFound();
            }

            var viewModel = new OfficialSealApplicationViewModel
            {
                Id = officialSealApplication.Id,
                ApplicantName = officialSealApplication.ApplicantName,
                ApplicantDepartment = officialSealApplication.ApplicantDepartment,
                ApplicationDate = officialSealApplication.ApplicationDate,
                SealType = officialSealApplication.SealType,
                Reason = officialSealApplication.Reason,
                UsageStartDate = officialSealApplication.UsageStartDate,
                UsageEndDate = officialSealApplication.UsageEndDate,
                Quantity = officialSealApplication.Quantity,
                AttachedFilesInfo = officialSealApplication.AttachedFilesInfo,
                WorkTaskId = officialSealApplication.WorkTaskId,
                CreatedTime = officialSealApplication.CreatedTime,
                UpdatedTime = officialSealApplication.UpdatedTime,
                CreatorUserId = officialSealApplication.CreatorUserId
            };

            await PopulateWorkTaskStatusAsync(viewModel, officialSealApplication.Id.ToString(), officialSealApplication.WorkTaskId);

            return View(viewModel);
        }

        // GET: OfficialSealApplication/Create
        public IActionResult Create()
        {
            var model = new OfficialSealApplicationViewModel
            {
                ApplicationDate = DateTime.Now,
                UsageStartDate = DateTime.Now,
                UsageEndDate = DateTime.Now.AddDays(7),
                Quantity = 1
            };
            return View(model);
        }

        // POST: OfficialSealApplication/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(OfficialSealApplicationViewModel model)
        {
            if (ModelState.IsValid)
            {
                var officialSealApplication = new OfficialSealApplication
                {
                    ApplicantName = model.ApplicantName,
                    ApplicantDepartment = model.ApplicantDepartment,
                    ApplicationDate = model.ApplicationDate,
                    SealType = model.SealType,
                    Reason = model.Reason,
                    UsageStartDate = model.UsageStartDate,
                    UsageEndDate = model.UsageEndDate,
                    Quantity = model.Quantity,
                    AttachedFilesInfo = model.AttachedFilesInfo,
                    CreatedTime = DateTime.Now,
                    UpdatedTime = DateTime.Now,
                    CreatorUserId = CurrentUserId // From BaseController
                };
                _context.Add(officialSealApplication);
                await _context.SaveChangesAsync();
                // TempData["SuccessMessage"] = "申请创建成功！"; // Optional: Add success message
                return RedirectToAction(nameof(Index));
            }
            return View(model);
        }

        // GET: OfficialSealApplication/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var officialSealApplication = await _context.OfficialSealApplications.FindAsync(id);
            if (officialSealApplication == null)
            {
                return NotFound();
            }

            var viewModel = new OfficialSealApplicationViewModel
            {
                Id = officialSealApplication.Id,
                ApplicantName = officialSealApplication.ApplicantName,
                ApplicantDepartment = officialSealApplication.ApplicantDepartment,
                ApplicationDate = officialSealApplication.ApplicationDate,
                SealType = officialSealApplication.SealType,
                Reason = officialSealApplication.Reason,
                UsageStartDate = officialSealApplication.UsageStartDate,
                UsageEndDate = officialSealApplication.UsageEndDate,
                Quantity = officialSealApplication.Quantity,
                AttachedFilesInfo = officialSealApplication.AttachedFilesInfo,
                WorkTaskId = officialSealApplication.WorkTaskId
                // CreatedTime, UpdatedTime, CreatorUserId are not typically edited, but can be included if needed for display on edit form
            };

            await PopulateWorkTaskStatusAsync(viewModel, officialSealApplication.Id.ToString(), officialSealApplication.WorkTaskId);

            // Permission Check: Only allow edit if WorkTaskId is null/empty (draft) OR if status is Pending
            if (!string.IsNullOrEmpty(viewModel.WorkTaskId) && viewModel.CurrentWorkTaskStatus != WorkTaskStatus.Pending.ToString())
            {
                TempData["ErrorMessage"] = $"申请 (ID: {viewModel.Id}) 的状态为 “{viewModel.CurrentWorkTaskStatusDisplay}”，不允许编辑。";
                return RedirectToAction(nameof(Details), new { id = viewModel.Id });
            }

            return View(viewModel);
        }

        // POST: OfficialSealApplication/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, OfficialSealApplicationViewModel viewModel)
        {
            if (id != viewModel.Id)
            {
                return NotFound();
            }

            var officialSealApplication = await _context.OfficialSealApplications.FindAsync(id);
            if (officialSealApplication == null)
            {
                return NotFound();
            }

            // Populate status for permission check before saving
            // Use a temporary ViewModel or directly populate properties on the passed viewModel
            // to avoid modifying it if validation fails early.
            // For this check, we only need Id and WorkTaskId from the entity.
            var statusCheckViewModel = new OfficialSealApplicationViewModel { Id = officialSealApplication.Id, WorkTaskId = officialSealApplication.WorkTaskId };
            await PopulateWorkTaskStatusAsync(statusCheckViewModel, officialSealApplication.Id.ToString(), officialSealApplication.WorkTaskId);

            if (!string.IsNullOrEmpty(statusCheckViewModel.WorkTaskId) && statusCheckViewModel.CurrentWorkTaskStatus != WorkTaskStatus.Pending.ToString())
            {
                TempData["ErrorMessage"] = $"申请 (ID: {statusCheckViewModel.Id}) 的状态为 “{statusCheckViewModel.CurrentWorkTaskStatusDisplay}”，不允许编辑。";
                // If returning to View, repopulate the original viewModel with current status for display
                await PopulateWorkTaskStatusAsync(viewModel, officialSealApplication.Id.ToString(), officialSealApplication.WorkTaskId);
                return View(viewModel);
            }

            if (ModelState.IsValid)
            {
                try
                {
                    // officialSealApplication already fetched
                    officialSealApplication.ApplicantName = viewModel.ApplicantName;
                    officialSealApplication.ApplicantDepartment = viewModel.ApplicantDepartment;
                    officialSealApplication.ApplicationDate = viewModel.ApplicationDate;
                    officialSealApplication.SealType = viewModel.SealType;
                    officialSealApplication.Reason = viewModel.Reason;
                    officialSealApplication.UsageStartDate = viewModel.UsageStartDate;
                    officialSealApplication.UsageEndDate = viewModel.UsageEndDate;
                    officialSealApplication.Quantity = viewModel.Quantity;
                    officialSealApplication.AttachedFilesInfo = viewModel.AttachedFilesInfo;
                    officialSealApplication.UpdatedTime = DateTime.Now;
                    // WorkTaskId is not changed here

                    _context.Update(officialSealApplication);
                    await _context.SaveChangesAsync();
                    TempData["SuccessMessage"] = "申请更新成功！";
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!OfficialSealApplicationExists(viewModel.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            // If ModelState is invalid, repopulate status for display before returning view
            await PopulateWorkTaskStatusAsync(viewModel, officialSealApplication.Id.ToString(), officialSealApplication.WorkTaskId);
            return View(viewModel);
        }

        // GET: OfficialSealApplication/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var officialSealApplication = await _context.OfficialSealApplications
                .FirstOrDefaultAsync(m => m.Id == id);

            if (officialSealApplication == null)
            {
                return NotFound();
            }

            var viewModel = new OfficialSealApplicationViewModel // Use ViewModel for consistency and to pass status
            {
                Id = officialSealApplication.Id,
                ApplicantName = officialSealApplication.ApplicantName,
                ApplicantDepartment = officialSealApplication.ApplicantDepartment,
                ApplicationDate = officialSealApplication.ApplicationDate,
                SealType = officialSealApplication.SealType,
                Reason = officialSealApplication.Reason,
                UsageStartDate = officialSealApplication.UsageStartDate,
                UsageEndDate = officialSealApplication.UsageEndDate,
                Quantity = officialSealApplication.Quantity,
                AttachedFilesInfo = officialSealApplication.AttachedFilesInfo,
                WorkTaskId = officialSealApplication.WorkTaskId,
                CreatedTime = officialSealApplication.CreatedTime,
                UpdatedTime = officialSealApplication.UpdatedTime,
                CreatorUserId = officialSealApplication.CreatorUserId
            };

            await PopulateWorkTaskStatusAsync(viewModel, officialSealApplication.Id.ToString(), officialSealApplication.WorkTaskId);

            // Permission Check: Only allow delete if WorkTaskId is null/empty (draft) OR if status is Pending
            if (!string.IsNullOrEmpty(viewModel.WorkTaskId) && viewModel.CurrentWorkTaskStatus != WorkTaskStatus.Pending.ToString())
            {
                TempData["ErrorMessage"] = $"申请 (ID: {viewModel.Id}) 的状态为 “{viewModel.CurrentWorkTaskStatusDisplay}”，不允许删除。";
                return RedirectToAction(nameof(Details), new { id = viewModel.Id });
            }
            
            // It's better to pass the ViewModel to the Delete confirmation view 
            // so it can display details including the status if needed, or at least be consistent.
            // However, the default scaffolded Delete view might expect the entity directly.
            // For now, let's assume the Delete view can handle OfficialSealApplicationViewModel or we'll adjust it later.
            // If Delete.cshtml strictly expects OfficialSealApplication, then we might need a different approach for passing status,
            // or just show the error and redirect without showing the delete confirmation page.
            // Given the redirect above, this View(viewModel) might only be reached if deletion is allowed.
            return View(viewModel); 
        }

        // POST: OfficialSealApplication/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var officialSealApplication = await _context.OfficialSealApplications.FindAsync(id);
            if (officialSealApplication == null)
            {
                return NotFound(); // Or TempData message and redirect
            }

            // Populate status for permission check before deleting
            var statusCheckViewModel = new OfficialSealApplicationViewModel { Id = officialSealApplication.Id, WorkTaskId = officialSealApplication.WorkTaskId };
            await PopulateWorkTaskStatusAsync(statusCheckViewModel, officialSealApplication.Id.ToString(), officialSealApplication.WorkTaskId);

            if (!string.IsNullOrEmpty(statusCheckViewModel.WorkTaskId) && statusCheckViewModel.CurrentWorkTaskStatus != WorkTaskStatus.Pending.ToString())
            {
                TempData["ErrorMessage"] = $"申请 (ID: {statusCheckViewModel.Id}) 的状态为 “{statusCheckViewModel.CurrentWorkTaskStatusDisplay}”，不允许删除。";
                return RedirectToAction(nameof(Details), new { id = statusCheckViewModel.Id });
            }

            _context.OfficialSealApplications.Remove(officialSealApplication);
            await _context.SaveChangesAsync();
            TempData["SuccessMessage"] = "申请删除成功！";
            return RedirectToAction(nameof(Index));
        }

        private bool OfficialSealApplicationExists(int id)
        {
            return _context.OfficialSealApplications.Any(e => e.Id == id);
        }

        // GET: OfficialSealApplication/SubmitForApprovalDoc
        public IActionResult SubmitForApprovalDoc()
        {
            ViewData["Title"] = "公章申请审批流程文档";
            return View();
        }

        // GET: OfficialSealApplication/WorkflowWidgetIntegrationDoc
        public IActionResult WorkflowWidgetIntegrationDoc()
        {
            ViewData["Title"] = "流程引擎小部件集成文档";
            return View();
        }

        /// <summary>
        /// 显示公开链接功能说明文档
        /// </summary>
        /// <returns>说明文档页面</returns>
        // GET: OfficialSealApplication/PublicLinkDoc
        public IActionResult PublicLinkDoc()
        {
            ViewData["Title"] = "公开链接功能说明文档";
            ViewData["Description"] = "详细介绍公开链接提交审批功能的特性、技术原理和使用方法";
            return View();
        }

        // POST: OfficialSealApplication/SubmitForApproval/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> SubmitForApproval(int id)
        {
            return await SubmitForApprovalInternal(id, usePublicLink: false);
        }

        // POST: OfficialSealApplication/SubmitForApprovalWithPublicLink/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> SubmitForApprovalWithPublicLink(int id)
        {
            return await SubmitForApprovalInternal(id, usePublicLink: true);
        }

        // 内部通用方法
        private async Task<IActionResult> SubmitForApprovalInternal(int id, bool usePublicLink)
        {
            var officialSealApplication = await _context.OfficialSealApplications.FindAsync(id);

            if (officialSealApplication == null)
            {
                TempData["ErrorMessage"] = "未找到指定的申请记录。";
                return RedirectToAction(nameof(Index));
            }

            // Permission Check
            var currentUserId = CurrentEmployeeNumber; // Assuming CurrentUserId is available from BaseController
            if (string.IsNullOrEmpty(currentUserId))
            {
                TempData["ErrorMessage"] = "无法获取当前用户信息，请重新登录后尝试。";
                return RedirectToAction(nameof(Details), new { id = officialSealApplication.Id });
            }

            // 1. Create WorkTask
            var createDto = new CreateWorkTaskWithDefaultVersionInputDto
            {
                EntityFullName = "OfficialSealApplication", // As defined in the plan
                EntityKeyValue = officialSealApplication.Id.ToString(),
                Name = $"公章使用申请 - {officialSealApplication.ApplicantName} - {officialSealApplication.SealType}", // Corrected property: Name
                WorkflowNo = "WF20250528224424816", // TODO: Replace with actual Workflow Definition ID for "OfficialSealApplication"
                FormData = JsonConvert.SerializeObject(officialSealApplication), // Serialize the application data to JSON
                FormLink = usePublicLink
                    ? $"{Request.Scheme}://{Request.Host}/OfficialSealApplication/PublicDetails/{officialSealApplication.Id}"
                    : null // 现有逻辑保持FormLink为null或空
            };

            
              // 检查是否已存在相同entity的记录
            var existingState = await _context.WorkTaskStateInfos
                .FirstOrDefaultAsync(s =>
                    s.EntityFullName == "OfficialSealApplication" &&
                    s.EntityKeyValue == officialSealApplication.Id.ToString());

            if (existingState != null)
            {
                var availableStatuses = new[] { WorkTaskStatus.Pending, WorkTaskStatus.Canceled };
                if (!availableStatuses.Contains(existingState.WorkTaskStatus))
                {
                    TempData["ErrorMessage"] = $"申请 (ID: {officialSealApplication.Id}) 的状态为 \"{existingState.WorkTaskStatus}\"，不允许重复提交。";
                    return RedirectToAction(nameof(Details), new { id = officialSealApplication.Id });
                }
            }
            else
            {
                // 如果不存在记录，则创建初始状态记录
                var initialState = new WorkTaskStateInfo
                {
                    EntityFullName = "OfficialSealApplication",
                    EntityKeyValue = officialSealApplication.Id.ToString(),
                    WorkTaskStatus = WorkTaskStatus.Pending,
                    ProcessName = createDto.Name,
                    CreatedTime = DateTime.Now,
                    CreatedUserId = CurrentUserId
                };
                _context.WorkTaskStateInfos.Add(initialState);
                await _context.SaveChangesAsync();
            }

            WorkTaskDto createTaskResponse;
            try
            {
                createTaskResponse = await _workTaskAdapterService.CreateWorkTaskWithDefaultVersionAsync(createDto);
            }
            catch (Exception ex)
            {
                // Log the exception (ex)
                TempData["ErrorMessage"] = $"创建工作任务失败：{ex.Message}";
                return RedirectToAction(nameof(Details), new { id = officialSealApplication.Id });
            }

            if (createTaskResponse == null || createTaskResponse.Id == Guid.Empty) // Corrected check for Guid
            {
                TempData["ErrorMessage"] = "创建工作任务失败，未能获取任务ID。";
                return RedirectToAction(nameof(Details), new { id = officialSealApplication.Id });
            }

            officialSealApplication.WorkTaskId = createTaskResponse.Id.ToString(); // Convert Guid to string for storage
            _context.Update(officialSealApplication);
            
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException ex)
            {
                // Log the exception (ex)
                TempData["ErrorMessage"] = $"更新申请记录的WorkTaskId失败：{ex.Message}";
                // Optionally, consider if the created WorkTask should be cancelled or handled
                return RedirectToAction(nameof(Details), new { id = officialSealApplication.Id });
            }

            // 2. Start WorkTask
            var startDto = new StartWorkTaskInputDto
            {
                WorktaskId = createTaskResponse.Id // Corrected property: WorktaskId, and it's a Guid
                // StartUserId and Variables are typically handled by the service or not required by this DTO
            };

            StartWorkTaskOutputDto startTaskResponse;
            try
            {
                startTaskResponse = await _workTaskAdapterService.StartWorkTaskAsync(startDto);
            }
            catch (Exception ex)
            {
                // Log the exception (ex)
                TempData["ErrorMessage"] = $"发起工作流程失败：{ex.Message}";
                // At this point, WorkTaskId is saved. Consider the implications or a compensation mechanism if critical.
                return RedirectToAction(nameof(Details), new { id = officialSealApplication.Id });
            }

            // Assuming StartWorkTaskOutputDto has a boolean Success property or similar
            // For now, we'll assume if no exception, it's successful or we check specific properties of startTaskResponse
            // if (startTaskResponse == null || !startTaskResponse.Success) // Adjust based on actual DTO
            // {
            //     TempData["ErrorMessage"] = "发起工作流程失败。";
            //     return RedirectToAction(nameof(Details), new { id = officialSealApplication.Id });
            // }

            string successMessage = usePublicLink
                ? "申请已成功提交审批（使用公开链接）！"
                : "申请已成功提交审批！";
            TempData["SuccessMessage"] = successMessage;
            return RedirectToAction(nameof(Details), new { id = officialSealApplication.Id });
        }
    }
}
